package com.integral.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.integral.system.dao.SysUserDao;
import com.integral.system.dao.SysUserRoleDao;
import com.integral.system.domain.SysUserDo;
import com.integral.system.domain.SysUserRoleDo;
import com.integral.system.position.dao.CfgPositionIntegralDao;
import com.integral.system.position.domain.CfgPositionIntegralDo;
import com.integral.system.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUserDo> implements SysUserService {
    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private SysUserRoleDao sysUserRoleDao;
    @Autowired
    private CfgPositionIntegralDao cfgPositionIntegralDao;
    @Override
    public SysUserDo getUserByName(String userName) {
        QueryWrapper<SysUserDo> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotEmpty(userName)){
            queryWrapper.eq("user_account",userName);
            SysUserDo user = sysUserDao.selectOne(queryWrapper);
            String menus = getMenusByUser(user.getUserNo());
            user.setMenus(menus);
            return user;
        }else {
            log.error("[######查询用户失败,传入的用户名为空######]");
            return  null;
        }
    }

    public String getMenusByUser(Long userNo){
        StringBuilder menusBuilder = new StringBuilder();
        List<String> roleIds = new ArrayList<>();
        QueryWrapper<SysUserRoleDo> roleDoQueryWrapper = new QueryWrapper<>();
        roleDoQueryWrapper.eq("user_no",userNo);
        List<SysUserRoleDo> roles = sysUserRoleDao.selectList(roleDoQueryWrapper);
        for (SysUserRoleDo role : roles) {
            roleIds.add(role.getRoleNo());
        }
        if (roles.size() == 0){
            return "";
        }
        QueryWrapper<CfgPositionIntegralDo> positionWrapper = new QueryWrapper<>();
        positionWrapper.in("position_no",roleIds);
        List<CfgPositionIntegralDo> positions = cfgPositionIntegralDao.selectList(positionWrapper);
        for (CfgPositionIntegralDo position : positions) {
            menusBuilder.append(position.getMenus()).append(",");
        }
        String meus = menusBuilder.toString();
        if (meus.endsWith(",")){
            meus.substring(0,meus.length()-1); // 去掉末尾 ,
        }
        return meus;
    }
}
